package com.xyy.saas.payment.payment.core.service;

import com.alibaba.fastjson.JSONObject;
import com.xyy.saas.payment.adpater.fumin.config.CertConstants;
import com.xyy.saas.payment.adpater.fumin.spring.SpringConfiguration;
import com.xyy.saas.payment.adpater.fumin.util.VerifyAndDecryptUtil;
import com.xyy.saas.payment.api.impl.PaymentOrderApiImpl;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.common.enums.FBankTradeTypeEnum;
import com.xyy.saas.payment.cores.enums.BusinessIdTypeEnum;
import com.xyy.saas.payment.cores.enums.BusinessTypeEnum;
import com.xyy.saas.payment.cores.vo.SeparateAccountFromUserVo;
import com.xyy.saas.payment.dao.model.PayAccount;
import com.xyy.saas.payment.dao.model.ThirdUserInfo;
import com.xyy.saas.payment.payment.core.dto.VirtualAccountDto;
import com.xyy.saas.payment.service.PayAccountService;
import com.xyy.saas.payment.service.ThirdUserInfoService;
import com.xyy.saas.payment.util.AmountCastUtil;
import com.xyy.saas.payment.util.ApolloUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * 动账通知处理
 */
@Slf4j
@Service
public class DealVirtualAccountChangeService {
    @Resource
    private SpringConfiguration springConfiguration;
    @Resource
    private FrozenSettlementService frozenSettlementService;
    @Resource
    private PaymentOrderApiImpl paymentOrderApi;
    @Resource
    private PayAccountService payAccountService;
    @Resource
    private ThirdUserInfoService thirdUserInfoService;

    /**
     * 资金冻结
     * @param ciphertext
     */
    public void deal(String ciphertext) {
        try {
            // 忽略富民2.0系统的通知
            if(ciphertext.contains(CertConstants.ALGORITHM_RSAV2)) {
                log.info("DealVirtualAccountChangeService#deal，ignore fbank v2, ciphertext={}", JSONObject.toJSONString(ciphertext));
                return;
            }

            // 1.解析参数
            String signResult = VerifyAndDecryptUtil.decryptResult(JSONObject.parseObject(ciphertext), springConfiguration.privateKey());
            VirtualAccountDto virtualAccountDto = JSONObject.parseObject(signResult, VirtualAccountDto.class);
            log.info("DealVirtualAccountChangeService#deal，start, ciphertext={}", JSONObject.toJSONString(virtualAccountDto));

            if(FBankTradeTypeEnum.SETTLE.getType().equals(virtualAccountDto.getTrade_type())) {
                // 药帮忙平台账户走转账流程
                if(ApolloUtil.getProperty(Constants.FBANK_YBM_TECH_ACCOUNT_NO, StringUtils.EMPTY).contains(virtualAccountDto.getAccount_no())) {
                    transferBalance(virtualAccountDto);
                }
                // 荷叶平台账户走转账流程
                else if(ApolloUtil.getProperty(Constants.FBANK_HEYE_ACCOUNT_NO, StringUtils.EMPTY).contains(virtualAccountDto.getAccount_no())) {
                    transferBalanceByHeye(virtualAccountDto);
                }
                // 非平台账户走冻结流程
                else {
                    ThirdUserInfo thirdUserInfo = thirdUserInfoService.getThirdUserInfoByUserId(virtualAccountDto.getCust_merchant_no());

                    // 已切平安商户走转账
                    if(Constants.PINGAN.equals(thirdUserInfo.getThirdType())) {
                        virtualAccountDto.setCust_merchant_no(virtualAccountDto.getCust_merchant_no() + PayAccount.SUFFIX_DELETE);
                        transferBalance(virtualAccountDto);
                    }
                    // 未切平安商户走冻结
                    else {
                        frozenSettlementService.frozenBalance(virtualAccountDto);
                    }
                }
            }
            else if(FBankTradeTypeEnum.RECHARGE.getType().equals(virtualAccountDto.getTrade_type()) &&
                    ApolloUtil.getProperty(Constants.FBANK_XYY_WH_ACCOUNT_ID, StringUtils.EMPTY).equals(virtualAccountDto.getCust_merchant_no()))
            {
                transferBalance(virtualAccountDto);
            }
            else {
                log.warn("deal#frozenBalance, ignore trade type, signResult={}", JSONObject.toJSONString(virtualAccountDto));
            }
        }
        catch(Exception ex) {
            log.error(ex.getMessage() + ", ciphertext=" + ciphertext ,ex);
        }
    }

    /**
     * 药帮忙平台轮训账户->药帮忙平台结算账户
     * @param virtualAccountDto
     */
    private void transferBalance(VirtualAccountDto virtualAccountDto) {
        SeparateAccountFromUserVo account = new SeparateAccountFromUserVo();
        account.setBusinessOrderNo(virtualAccountDto.getDirection() +  virtualAccountDto.getTrade_no());
        account.setBusinessType(BusinessTypeEnum.EC.getType());
        account.setBusinessIdType(BusinessIdTypeEnum.EC_POP.getType());
        account.setBusinessOrderType(BusinessIdTypeEnum.EC_POP.getType());

        PayAccount outPayAccount = payAccountService.getPayAccountByAccountId(virtualAccountDto.getCust_merchant_no());
        account.setBusinessUserIdOut(outPayAccount.getBusinessUserId());
        account.setBusinessUserIdIn("ec_pop_platform");
        account.setBusinessIdTypeOut(outPayAccount.getBusinessIdType());
        account.setBusinessIdTypeIn(BusinessIdTypeEnum.EC_POP.getType());

        account.setAmount(AmountCastUtil.castYuan2Fen(virtualAccountDto.getAmount()));

        account.setInvoker(StringUtils.EMPTY);
        account.setExtra("平台收款账户TO平台结算账户");
        paymentOrderApi.separateAccountFromUser(account, StringUtils.EMPTY);
    }

    /**
     * 荷叶平台轮训账户->荷叶平台结算账户
     * @param virtualAccountDto
     */
    private void transferBalanceByHeye(VirtualAccountDto virtualAccountDto) {
        SeparateAccountFromUserVo account = new SeparateAccountFromUserVo();
        account.setBusinessOrderNo(virtualAccountDto.getDirection() +  virtualAccountDto.getTrade_no());
        account.setBusinessType(BusinessTypeEnum.YIKUAIQIAN.getType());
        account.setBusinessIdType(BusinessIdTypeEnum.YIKUAIQIAN_FM.getType());
        account.setBusinessOrderType(BusinessIdTypeEnum.YIKUAIQIAN_FM.getType());

        account.setBusinessUserIdOut(payAccountService.getBusinessUserIdByAccountId(virtualAccountDto.getCust_merchant_no()));
        account.setBusinessUserIdIn("yikuaiqian_fm_platform");
        account.setBusinessIdTypeOut(BusinessIdTypeEnum.YIKUAIQIAN_FM.getType());
        account.setBusinessIdTypeIn(BusinessIdTypeEnum.YIKUAIQIAN_FM.getType());

        account.setAmount(AmountCastUtil.castYuan2Fen(virtualAccountDto.getAmount()));

        account.setInvoker(StringUtils.EMPTY);
        account.setExtra("荷叶平台轮训账户TO荷叶平台结算账户");
        paymentOrderApi.separateAccountFromUser(account, StringUtils.EMPTY);
    }
}
